package com.information.controller;

import com.information.entity.User;
import com.information.service.IpBlacklistService;
import com.information.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/blacklist")
// 移除这行：@CrossOrigin(origins = "*")
public class IpBlacklistController {
    
    @Autowired
    private IpBlacklistService ipBlacklistService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取当前操作人用户名
     * @param request
     */
    private String getOperator(HttpServletRequest request) {
        // 从请求头获取用户名
        String username = request.getHeader("X-Username");

        // 如果请求头中没有，则尝试从请求参数中获取
        if (username == null || username.isEmpty()) {
            username = request.getParameter("operatedBy");
        }

        // 如果都没有，则使用默认值
        if (username == null || username.isEmpty()) {
            username = "system";
        }

        return username;
    }

    /**
     * 获取黑名单列表
     * @param request
     */
    @GetMapping
    public ResponseEntity<?> getAllBlacklist(HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));
            
            if (operator.getRole() != User.UserRole.ADMIN && operator.getRole() != User.UserRole.SUPER_ADMIN) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：只有管理员可以查看黑名单");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }
            
            List<String> blacklist = ipBlacklistService.getAllBlacklistedIps();
            Map<String, Object> response = new HashMap<>();
            response.put("data", blacklist);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "获取黑名单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 添加黑名单成员
     * @param request
     * @param httpRequest
     */
    @PostMapping
    public ResponseEntity<?> addToBlacklist(@RequestBody Map<String, String> request,
                                          HttpServletRequest httpRequest) {
        try {
            String operatedBy = getOperator(httpRequest);
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            if (operator.getRole() != User.UserRole.ADMIN && operator.getRole() != User.UserRole.SUPER_ADMIN) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：只有管理员可以添加黑名单");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            String ipAddress = request.get("ipAddress");
            ipBlacklistService.addToBlacklist(ipAddress, operatedBy);

            // 添加成功后，返回更新后的IP列表
            List<String> updatedBlacklist = ipBlacklistService.getAllBlacklistedIps();
            Map<String, Object> response = new HashMap<>();
            response.put("message", "IP已添加到黑名单");
            response.put("data", updatedBlacklist);
            return ResponseEntity.ok(response);

        } catch (RuntimeException e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "添加黑名单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 从黑名单移除成员
     * @param ipAddress
     * @param request
     */
    @DeleteMapping
    public ResponseEntity<?> removeFromBlacklist(@RequestParam String ipAddress,
                                               HttpServletRequest request) {
        try {
            String operatedBy = getOperator(request);
            User operator = userService.findUserByUsername(operatedBy)
                    .orElseThrow(() -> new RuntimeException("操作者未找到: " + operatedBy));

            if (operator.getRole() != User.UserRole.ADMIN && operator.getRole() != User.UserRole.SUPER_ADMIN) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "权限不足：只有管理员可以移除黑名单");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
            }

            ipBlacklistService.removeFromBlacklist(ipAddress, operatedBy);

            // 删除成功后，返回更新后的IP列表
            List<String> updatedBlacklist = ipBlacklistService.getAllBlacklistedIps();
            Map<String, Object> response = new HashMap<>();
            response.put("message", "IP已从黑名单移除");
            response.put("data", updatedBlacklist);
            return ResponseEntity.ok(response);

        } catch (RuntimeException e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "移除黑名单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
}